function BHVR_Plot2AFC_TTP3(ax,schedule)
% BHVR_Plot2AFC_TTP3(ax,schedule)
% 
% Plot running hit rate
% 
% DJS (2012)
rv = schedule.response_vals;

rcidx = regexp(schedule.readparams,'response_code');
rcidx = findincell(rcidx) + 1;
ttidx = regexp(schedule.readparams,'trial_type');
ttidx = findincell(ttidx) + 1;
% hpidx = findincell(regexp(schedule.readparams,'HPFreq'));

vals   = rv(:,rcidx); vals(isnan(vals))     = [];
trials = rv(:,ttidx); trials(isnan(trials)) = [];
% freqs  = rv(:,hpidx); freqs(isnan(freqs))   = [];


% hits = bitget(vals,6);

% LEFT: bit 3(2) ; RIGHT: bit 4(3)
% AM State = 2
AMleft  = bitget(vals,3) & bitget(vals,13);
AMright = bitget(vals,4) & bitget(vals,13);

% Quiet State = 1
Qleft  = bitget(vals,3) & bitget(vals,12);
Qright = bitget(vals,4) & bitget(vals,12);

% Tone State = 0
Tleft  = bitget(vals,3) & bitget(vals,11);
Tright = bitget(vals,4) & bitget(vals,11);

amind = AMleft|AMright;
qind  = Qright|Qleft;
tind  = Tleft |Tright;

if numel(AMleft) == 1, return; end

% totals
% r = sum([AMleft AMright Qright Qleft Tleft Tright]);
% AMhr = r(1)/sum(r([1 2]))*100;
% Qhr  = r(3)/sum(r([3 4]))*100;
% Thr  = r(5)/sum(r([5 6]))*100;
% Ohr  = sum(hits|Qright)/length(hits)*100;
 
% % print results to command window
% fprintf('\n%s\n',schedule.schedule);
% fprintf('\tHit\t\Tright\tHR\n')
% fprintf('AM\t%d\t\t%d\t\t%3.1f%%\n',r([1 2]),AMhr)
% fprintf('Q\t%d\t\t%d\t\t%3.1f%%\n', r([3 4]),Qhr)
% fprintf('T\t%d\t\t%d\t\t%3.1f%%\n', r([5 6]),Thr)
% fprintf('#trials = %3.0f\t\t%3.1f%%%s\n\n',sum(r),Ohr,festr);


% plot by trials


cla(ax)
hold(ax,'on')
grid(ax,'on')

amy = cumsum(AMright)./ cumsum(amind) * 100;
qy  = cumsum(Qright) ./ cumsum(qind)  * 100;
ty  = cumsum(Tleft)  ./ cumsum(tind)  * 100;


plot(ax,find(amind&AMright),amy(amind&AMright), 'ob','markersize',7,'markerfacecolor','b');
plot(ax,find(qind&Qright),  qy(qind&Qright),    'or','markersize',7,'markerfacecolor','r');
plot(ax,find(tind&Tleft),   ty(tind&Tleft),     'og','markersize',7,'markerfacecolor','g');
plot(ax,find(amind&AMleft), amy(amind&AMleft),  'xb','markersize',10);
plot(ax,find(qind&Qleft),   qy(qind&Qleft),     'xr','markersize',10);
plot(ax,find(tind&Tright),  ty(tind&Tright),    'xg','markersize',10);

plot(ax,[0 length(trials)],[50 50],'-k');

xlim(ax,[0 length(trials)]); ylim(ax,[-10 110]);
set(ax,'ytick',[0 25 50 75 100]);
xlabel(ax,'Trial number');  ylabel(ax,'Hit rate');
box(ax,'on')
hold(ax,'off')
% legend(sprintf('AM (%0.1f%%)',AMhr),sprintf('Quiet (%0.1f%%)',Qhr),sprintf('Tone (%0.1f%%)',Thr), ...
%     'Overall','location','best')

